/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UI.DocumentPanel;

import Common.IDocument;
import Common.IDocumentCollection;
import ComponentsUI.IPrimitiveUI;
import Project.DocumentCollection;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;

/**
 *
 * @author Администратор
 */
public class DocumentTabbedPane extends JTabbedPane {

    private IDocumentCollection documentCollection;
    Point activPoint;
    int activeTab;
    public DocumentTabbedPane() {

        documentCollection = new DocumentCollection();
        activPoint = new Point();

        this.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                documentTabbedPaneMouseClicked(e);
            }
        });
    }

    private void documentTabbedPaneMouseClicked(MouseEvent e) {
        activPoint.x = e.getX();
        activPoint.y = e.getY();
        activeTab = ((JTabbedPane) e.getSource()).getSelectedIndex();
        
        switch (e.getButton()) {
            case MouseEvent.BUTTON1:
                mouseLeftClicked(e);
        }

    }

    private void mouseLeftClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            Component component = ((JScrollPane) this.getSelectedComponent()).getViewport().getComponentAt(e.getPoint());
            if (component instanceof DocumentPanel) {
                this.documentCollection.remove(this.getDocumentPanel().getDocument());
                this.remove(this.getActivTab());
            }
        }
    }

    public DocumentPanel getDocumentPanel() {
        return (DocumentPanel)((JScrollPane) this.getSelectedComponent()).getViewport().getComponentAt(activPoint);
    }

    private int getActivTab()
    {
        return this.activeTab;
    }
    
    public void addDocument(IDocument document) {
        if (!this.documentCollection.contains(document)) {
            this.documentCollection.add(document);
            this.addTab(document.getName(), new JScrollPane(new DocumentPanel(document)));
            this.setSelectedIndex(this.getTabCount()-1);
        }
    }
}
